<script setup>
import {ref, onBeforeMount} from "vue";
import {cancelOrderAPI, deliveryOrderAPI, getOrderPageAPI, updateOrderAPI} from "@/api/order.js";
import TailPrice from "@/components/TailPrice.vue";
import {getDateTimeFormatNow} from "@/utils/DateUtils.js";
import {
  CANCEL, COMPLETE,
  getOrderStatusMsg,
  WAIT_COMMENT,
  WAIT_DELIVERY,
  WAIT_PAY,
  WAIT_RECEIVE
} from "@/constants/OrderStatus.js";
import {getProductCategoryPageAPI} from "@/api/product.js";
import {elErrorMessageTip} from "@/utils/MessageTipUtils.js";

const orders = ref([])
// let ordersTemp = []
const searchKw = ref('')
// 下拉选择选项
const selectOptions = [
  {label: '全部', value: ''},
  {label: getOrderStatusMsg(0), value: 0},
  {label: getOrderStatusMsg(1), value: 1},
  {label: getOrderStatusMsg(2), value: 2},
  {label: getOrderStatusMsg(3), value: 3},
  {label: getOrderStatusMsg(4), value: 4},
  {label: getOrderStatusMsg(5), value: 5},
]
// 下拉选择
const selectValue = ref(null)
// 分页数据与条件
const current = ref(1)
// 每页数据个数
const pageSize = ref(5)
const pageCnt = ref(0)
// 总页数
const size = ref(0)
const data = ref([])
const getOrderPage = async (current_, pageSize_, kw = null, status = null) => {
  const res = await getOrderPageAPI(current_, pageSize_, kw, status)
  if (res === null) return
  current.value = res.current
  pageSize.value = res.pageSize
  pageCnt.value = res.pageCnt
  size.value = res.size
  orders.value = res.data
  orders.value = orders.value.map(
      item => {
        item.allPrice = Math.round((item.productOptionPrice * item.num + item.freight) * 100) / 100
        return item
      }
  )
}
onBeforeMount(async () => {
  await getOrderPage(current.value, pageSize.value)
  // ordersTemp = orders.value
})
const searchByCondition = async () => {
  await getOrderPage(current.value, pageSize.value, searchKw.value, selectValue.value)
}
// 分页每页数据大小改变
const handlePageSizeChange = async (val) => {
  pageSize.value = val
  await searchByCondition()
}
// 当前页发生变化
const handleCurrentChange = async (val) => {
  current.value = val
  await searchByCondition()
}

const filterStatus = (value, row, column) => {
  return row.status === value
}

const onCancelOrder = async (status, id) => {
  ElMessageBox.confirm(
      '是否确认取消订单',
      '取消订单',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    // on confirm
    let res = null
    if (status === WAIT_PAY) {
      console.log(status, id)
      res = await updateOrderAPI(id, CANCEL)
    } else {
      res = await cancelOrderAPI(id, CANCEL)
    }
    if (res) {
      await searchByCondition()
    }
  })
}

const deliveryVisible = ref(false)
const deliveryOrder = ref({})
const logistics = ref('')
const clickDelivery = (order) => {
  deliveryOrder.value = order
  deliveryVisible.value = true
  // logistics.value = ''
}
const orderDelivery = async () => {
  if (logistics.value.length <= 0) {
    elErrorMessageTip('请填写物流单号')
    return
  }
  const res = await deliveryOrderAPI(deliveryOrder.value.id, WAIT_RECEIVE,  logistics.value)
  if (res) {
    await searchByCondition()
    deliveryVisible.value = false
    logistics.value = ''
  }
}

// const getAllPrice = (scope) => {
//   return Math.round((scope.row.productOptionPrice * scope.row.num + scope.row.freight) * 100) / 100
// }
</script>

<template>
  <div class="order">
    <el-affix target=".order" :offset="80">
      <div class="p-4 glass-container flex justify-between items-center">
        <div class="flex justify-start items-center">
          <el-select v-model="selectValue" class="" placeholder="订单状态">
            <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <div>
            <el-input class="ipt" v-model="searchKw" clearable
                      :maxlength="255"
                      @keydown.enter="searchByCondition"
                      show-word-limit placeholder="请输入搜索关键词"/>
          </div>
          <el-button type="primary" plain @click="searchByCondition">搜索</el-button>
        </div>
        <div>
        
        </div>
      </div>
    </el-affix>
    <div class="mt-4">
      <el-table :data="orders" stripe style="width: 100%" scrollbar-always-on max-height="700">
        <el-table-column prop="id" sortable fixed="left" label="订单编号" width="120"/>
        <el-table-column prop="logistics" label="物流单号" width="150"/>
        <el-table-column prop="title" label="商品名称" width="230"/>
        <el-table-column prop="productOptionName" label="商品选项" width="230"/>
        <el-table-column prop="productOptionImg" label="商品图片" width="150">
          <template #default="scope">
            <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.productOptionImg"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[scope.row.productOptionImg]"
                :initial-index="0"
                hide-on-click-modal
                close-on-press-escape
                preview-teleported
                fit="contain"
            />
          </template>
        </el-table-column>
        <el-table-column label="单价" prop="productOptionPrice" sortable width="100">
          <template #default="scope">
            <TailPrice :price="scope.row.productOptionPrice.toString()" :is-start="false"></TailPrice>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="购买数量" sortable width="120"/>
        <el-table-column label="运费" sortable prop="freight" width="80">
          <template #default="scope">
            ￥{{ scope.row.freight }}
          </template>
        </el-table-column>
        <el-table-column prop="allPrice" sortable label="总价" width="100"/>
        <!--<template #default="scope">-->
        <!--  <TailPrice :price="(getAllPrice(scope)).toString()" :is-start="false"></TailPrice>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column prop="delivery" label="发货地" width="180"/>
        <el-table-column prop="addressFrom" label="发货详细地址" width="230"/>
        <el-table-column prop="userId" label="用户 ID" width="80"/>
        <el-table-column prop="name" label="收货人" width="100"/>
        <el-table-column prop="phone" label="收货手机号" width="120"/>
        <el-table-column label="收货地" width="150">
          <template #default="scope">
            {{ scope.row.province }}/{{ scope.row.city }}/{{ scope.row.county }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="收货详细地址" width="180"/>
        <el-table-column sortable prop="createTime" label="订单创建时间" width="170">
          <template #default="scope">
            {{ getDateTimeFormatNow(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column sortable prop="updateTime" label="订单更新时间" width="170">
          <template #default="scope">
            {{ getDateTimeFormatNow(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column
            fixed="right" label="订单状态" width="110"
            :filters="[
            { text: getOrderStatusMsg(CANCEL), value: CANCEL },
            { text: getOrderStatusMsg(WAIT_PAY), value: WAIT_PAY },
            { text: getOrderStatusMsg(WAIT_DELIVERY), value: WAIT_DELIVERY },
            { text: getOrderStatusMsg(WAIT_RECEIVE), value: WAIT_RECEIVE },
            { text: getOrderStatusMsg(WAIT_COMMENT), value: WAIT_COMMENT },
            { text: getOrderStatusMsg(COMPLETE), value: COMPLETE },
          ]"
            :filter-method="filterStatus"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.status === CANCEL" type="info">{{ getOrderStatusMsg(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status === WAIT_PAY" type="warning">{{ getOrderStatusMsg(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status === WAIT_DELIVERY">{{ getOrderStatusMsg(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status === WAIT_RECEIVE" type="success">{{ getOrderStatusMsg(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status === WAIT_COMMENT" effect="dark">{{ getOrderStatusMsg(scope.row.status) }}</el-tag>
            <el-tag v-else-if="scope.row.status === COMPLETE" type="success" effect="dark">{{ getOrderStatusMsg(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <div>
              <el-button
                  type="primary"
                  size="small"
                  :disabled="scope.row.status !== WAIT_DELIVERY"
                  @click="clickDelivery(scope.row)"
              >订单发货
              </el-button>
            </div>
            <div class="mt-2">
              <el-button
                  type="danger"
                  size="small"
                  :disabled="scope.row.status !== WAIT_PAY && scope.row.status !== WAIT_DELIVERY"
                  @click="onCancelOrder(scope.row.status, scope.row.id)"
              >取消订单
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="fixed bottom-2 right-6 z-10 glass-container p-2 flex justify-end items-center">
      <el-pagination
          v-model:current-page="current"
          v-model:page-size="pageSize"
          :page-sizes="[1, 5, 10, 20, 30, 40]"
          :page-count="pageCnt"
          layout="sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog
        v-model="deliveryVisible"
        title="订单发货"
        width="30%"
    >
      <el-form label-position="right" label-width="170px">
        <el-form-item label="订单编号">{{ deliveryOrder.id }}</el-form-item>
        <el-form-item label="商品名称">{{ deliveryOrder.title }}</el-form-item>
        <el-form-item label="商品选项">{{ deliveryOrder.productOptionName }}</el-form-item>
        <el-form-item label="商品图片">
          <el-image
              style="width: 100px; height: 100px"
              :src="deliveryOrder.productOptionImg"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="[deliveryOrder.productOptionImg]"
              :initial-index="0"
              hide-on-click-modal
              close-on-press-escape
              preview-teleported
              fit="contain"
          />
        </el-form-item>
        <el-form-item label="购买数量">{{ deliveryOrder.num }}</el-form-item>
        <el-form-item label="单价">
          <TailPrice :price="deliveryOrder.productOptionPrice.toString()" :is-start="false"></TailPrice>
        </el-form-item>
        <el-form-item label="运费">￥{{ deliveryOrder.freight }}</el-form-item>
        <el-form-item label="总价">
          <TailPrice :price="deliveryOrder.allPrice.toString()" :is-start="false"></TailPrice>
        </el-form-item>
        <el-form-item label="发货地">{{ deliveryOrder.delivery }}</el-form-item>
        <el-form-item label="发货详细地址">{{ deliveryOrder.addressFrom }}</el-form-item>
        <el-form-item label="收货人">{{ deliveryOrder.name }}</el-form-item>
        <el-form-item label="收货手机号">{{ deliveryOrder.phone }}</el-form-item>
        <el-form-item label="收货地">{{ deliveryOrder.province }}/{{ deliveryOrder.city }}/{{ deliveryOrder.county }}</el-form-item>
        <el-form-item label="收货详细地址">{{ deliveryOrder.address }}</el-form-item>
        <el-form-item label="物流单号">
          <el-input v-model="logistics" placeholder="添加物流单号" maxlength="100" show-word-limit clearable></el-input>
        </el-form-item>
      </el-form>
      <div class="flex justify-end items-center" @click="orderDelivery">
        <el-button type="primary">订单发货</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>